﻿using ShowDesktopOneMonitor.Properties;
using System;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using Microsoft.Win32;

namespace ShowDesktopOneMonitor
{
    /// <summary>
    /// Util class for reading and writing to settings file
    /// </summary>
    static class SettingsManager
    {
        private static readonly Settings SETTINGS = Settings.Default;
        private const string AppName = "ShowDesktopOneMonitor";
        private const string StartupKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

        public static Keys ReadHotkey ()
        {
            return SETTINGS.HotKey;
        }
        public static KeyModifiers ReadKeyModifiers ()
        {
            KeyModifiers modifiers = SETTINGS.KeyModifiers[0];
            Array.ForEach(SETTINGS.KeyModifiers, m => modifiers |= m);
            return modifiers;
        }

        public static void Save () => SETTINGS.Save();

        public static bool IsStartupEnabled()
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(StartupKey))
                {
                    if (key != null)
                    {
                        return key.GetValue(AppName) != null;
                    }
                }
            }
            catch (Exception)
            {
                // 如果出现异常，返回false
            }
            return false;
        }

        public static void SetStartup(bool enable)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(StartupKey, true))
                {
                    if (key != null)
                    {
                        if (enable)
                        {
                            string exePath = Assembly.GetExecutingAssembly().Location;
                            string workingDir = Path.GetDirectoryName(exePath);
                            // 使用引号包裹路径，并指定工作目录
                            string startupCommand = $"\"{exePath}\"";
                            key.SetValue(AppName, startupCommand);
                        }
                        else
                        {
                            key.DeleteValue(AppName, false);
                        }
                    }
                }
            }
            catch (Exception)
            {
                // 处理异常
            }
        }
    }
}
